﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml;

namespace Players_info
{
    class Program
    {
        private class PlayerInfo
        {
            public int Id;
            public string Name;

            public PlayerInfo(XmlNode info)
            {
                this.Id = Convert.ToInt32(info.FirstChild["id"].InnerText);
                this.Name = info.FirstChild["displayName"].InnerText;
            }
        }

        static void Main()
        {
            //using (var client = new HttpClient())
            //{
            //    client.BaseAddress = new Uri("https://us.api.battle.net/");
            //    client.DefaultRequestHeaders.Accept.Clear();
            //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //    for (int i = 194439; i < 500000; i++)
            //    {
            //        HttpResponseMessage response = client.GetAsync(string.Format("sc2/ladder/{0}?apikey=zrxxcy3qzp8jcbgrce2es4yq52ew2k7r", i)).Result;
            //        if (response.IsSuccessStatusCode)
            //        {
            //            var json = response.Content.ReadAsStringAsync().Result;
            //            Console.WriteLine("Ladder found, id: {0}", i);
            //        }
            //        else
            //        {
            //            Console.WriteLine(i);
            //        }
            //    }
            //}

            for (int i = 194439; i < 500000; i++)
            {
                Console.WriteLine("Ladder id: {0}", i);
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://us.api.battle.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = client.GetAsync(string.Format("sc2/ladder/{0}?apikey=zrxxcy3qzp8jcbgrce2es4yq52ew2k7r", i)).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync().Result;
                        var data = JsonConvert.DeserializeXmlNode(json, "ladderMembers");

                        var players = from d in data.DocumentElement.ChildNodes.Cast<XmlNode>()
                                      select new PlayerInfo(d);

                        int j = 0;
                        foreach (PlayerInfo playerInfo in players)
                        {
                            j++;
                            using (var clientPlayer = new HttpClient())
                            {
                                clientPlayer.BaseAddress = new Uri("https://us.api.battle.net/");
                                clientPlayer.DefaultRequestHeaders.Accept.Clear();
                                clientPlayer.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                                HttpResponseMessage responsePlayer = client.GetAsync(string.Format("sc2/profile/{0}/1/{1}/matches?apikey=zrxxcy3qzp8jcbgrce2es4yq52ew2k7r", playerInfo.Id, playerInfo.Name)).Result;
                                if (responsePlayer.IsSuccessStatusCode)
                                {
                                    var jsonPlayer = responsePlayer.Content.ReadAsStringAsync().Result;
                                    var dataPlayer = JsonConvert.DeserializeXmlNode(jsonPlayer, "matches");
                                    var latestMatchDate = dataPlayer.DocumentElement.FirstChild["date"].InnerText;
                                    DateTime dt = new DateTime(1970, 1, 1);
                                    dt = dt.AddSeconds(Convert.ToInt64(latestMatchDate));                                    

                                    TimeSpan difference = DateTime.UtcNow - dt;
                                    if (difference < new TimeSpan(0, 15, 0))
                                    {
                                        Console.WriteLine("{0}: {1} - {2}", playerInfo.Id, playerInfo.Name, dt.ToString());
                                    }
                                    else
                                    {
                                        Console.WriteLine("Player in ladder id: {0}", j);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Console.Read();

          

            ////T data;

            //string url = "https://eu.api.battle.net/d3/profile/Tok-2360/index?locale=en&apikey=zrxxcy3qzp8jcbgrce2es4yq52ew2k7r";
            //var remainingTries = 10;
            //var myStr = "";
            //var httpClient = new HttpClient();

            //do
            //{
            //    var response = httpClient.GetAsync(url).Result;

            //    if (response.IsSuccessStatusCode)
            //    {
            //        var memoryStream = new MemoryStream();
            //        using (var responseStream = response.Content.ReadAsStreamAsync().Result)
            //        {
            //            responseStream.CopyTo(memoryStream);
            //        }
            //        memoryStream.Position = 0;

            //        var sr = new StreamReader(memoryStream);
            //        myStr = sr.ReadToEnd();
            //        Console.WriteLine(myStr);
            //    }

            //    remainingTries--;

            //} while (remainingTries > 0);

            //return data != null && data.IsValidObject() ? data : null;

            //string postData = "https://dev.battle.net/&scope=wow.profile&grant_type=authorization_code&redirect_uri=https://dev.battle.net/&code=<auth-code>";
            //byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //Uri target = new Uri(postData);
            //WebRequest request = WebRequest.Create(target);

            //request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = byteArray.Length;

            //using (var dataStream = request.GetRequestStream())
            //{
            //    dataStream.Write(byteArray, 0, byteArray.Length);
            //}

            //using (var response = (HttpWebResponse)request.GetResponse())
            //{

            //    var encoding = ASCIIEncoding.ASCII;
            //    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
            //    {
            //        string responseText = reader.ReadToEnd();

            //        JObject jsonobject = JObject.Parse(responseText);
            //        Console.WriteLine(jsonobject["access_token"].ToString());
            //        Console.Read();
            //    }
            //}
        }

        //static async Task RunAsync()
        //{
        //    using (var client = new HttpClient())
        //    {
        //        client.BaseAddress = new Uri("http://api.steampowered.com/");
        //        client.DefaultRequestHeaders.Accept.Clear();
        //        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //        HttpResponseMessage response = await client.GetAsync("ISteamApps/GetAppList/v2");
        //        if (response.IsSuccessStatusCode)
        //        {
        //            var json = await response.Content.ReadAsStringAsync();
        //            var data = JsonConvert.DeserializeXmlNode(json);

        //            var steamGames = from d in data.DocumentElement.ChildNodes.Cast<XmlNode>()
        //                             select new GameInfo(d);

        //            foreach (GameInfo gameInfo in steamGames)
        //            {
        //                Console.WriteLine("{0}: {1}", gameInfo.AppId, gameInfo.Name);
        //            }

        //            Console.Read();
        //        }
        //    }
        //}
    }
}
